<template>
  <div class="anime-history-container">
    <h1 class="page-title">我的播放历史</h1>

    <!-- 筛选和排序 -->
    <div class="filter-bar">
      <div class="filter-group">
        <label>排序方式：</label>
        <select v-model="sortOption" @change="sortHistory">
          <option value="recent">最近观看</option>
          <option value="oldest">最早观看</option>
          <option value="name">名称排序</option>
        </select>
      </div>

      <div class="filter-group">
        <label>筛选：</label>
        <select v-model="filterOption" @change="filterHistory">
          <option value="all">全部</option>
          <option value="watching">在看</option>
          <option value="finished">已看完</option>
          <option value="dropped">已弃番</option>
        </select>
      </div>

      <button class="clear-btn" @click="clearAllHistory">清空历史记录</button>
    </div>

    <!-- 历史记录列表 -->
    <div class="history-list">
      <div v-if="filteredHistory.length === 0" class="empty-tip">
        <p>暂无观看历史记录</p>
        <router-link to="/anime" class="browse-link">去浏览番剧</router-link>
      </div>

      <div v-else>
        <div v-for="item in paginatedHistory" :key="item.id" class="history-item">
          <div class="anime-cover">
            <img :src="item.cover" :alt="item.title" @error="handleImageError">
          </div>

          <div class="anime-info">
            <h3 class="anime-title">
              <router-link :to="`/anime/detail/${item.id}`">{{ item.title }}</router-link>
            </h3>

            <div class="meta-info">
              <span class="episode">看到第 {{ item.lastEpisode }} 集</span>
              <span class="progress">进度: {{ calculateProgress(item) }}%</span>
              <span class="status" :class="item.status">{{ getStatusText(item.status) }}</span>
            </div>

            <div class="watch-info">
              <span class="last-watch">最后观看: {{ formatDate(item.lastWatchTime) }}</span>
              <span class="total-watch">累计观看: {{ item.totalWatchTime }}分钟</span>
            </div>

            <div class="actions">
              <button class="continue-btn" @click="continueWatching(item)">
                <i class="icon-play"></i> 继续观看
              </button>
              <button class="remove-btn" @click="removeFromHistory(item.id)">
                <i class="icon-trash"></i> 移除
              </button>
            </div>
          </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination" v-if="filteredHistory.length > pageSize">
          <button
              @click="prevPage"
              :disabled="currentPage === 1"
              class="page-btn"
          >
            上一页
          </button>

          <span class="page-info">
            第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
          </span>

          <button
              @click="nextPage"
              :disabled="currentPage === totalPages"
              class="page-btn"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 模拟数据
const animeHistory = reactive([
  {
    id: 1,
    title: '咒术回战 第二季',
    cover: 'http://localhost:7150/src/assets/image/lbt3.png',
    lastEpisode: 5,
    totalEpisodes: 24,
    lastWatchTime: '2023-07-15T14:30:00',
    totalWatchTime: 125,
    status: 'watching'
  },
  {
    id: 2,
    title: '间谍过家家',
    cover: 'http://localhost:7150/src/assets/image/lbt3.png',
    lastEpisode: 12,
    totalEpisodes: 12,
    lastWatchTime: '2023-06-20T19:15:00',
    totalWatchTime: 240,
    status: 'finished'
  },
  {
    id: 3,
    title: '鬼灭之刃 刀匠村篇',
    cover: 'http://localhost:7150/src/assets/image/lbt3.png',
    lastEpisode: 8,
    totalEpisodes: 11,
    lastWatchTime: '2023-07-10T21:00:00',
    totalWatchTime: 180,
    status: 'watching'
  },
  {
    id: 4,
    title: '我推的孩子',
    cover: 'http://localhost:7150/src/assets/image/lbt3.png',
    lastEpisode: 1,
    totalEpisodes: 12,
    lastWatchTime: '2023-05-05T18:45:00',
    totalWatchTime: 24,
    status: 'dropped'
  },
  {
    id: 5,
    title: '进击的巨人 Final Season',
    cover: 'http://localhost:7150/src/assets/image/lbt3.png',
    lastEpisode: 28,
    totalEpisodes: 28,
    lastWatchTime: '2023-04-30T22:10:00',
    totalWatchTime: 672,
    status: 'finished'
  }
])

// 状态管理
const sortOption = ref('recent')
const filterOption = ref('all')
const currentPage = ref(1)
const pageSize = 3 // 每页显示3条记录

// 计算属性
const filteredHistory = computed(() => {
  let result = [...animeHistory]

  // 筛选
  if (filterOption.value !== 'all') {
    result = result.filter(item => item.status === filterOption.value)
  }

  // 排序
  switch (sortOption.value) {
    case 'recent':
      result.sort((a, b) => new Date(b.lastWatchTime) - new Date(a.lastWatchTime))
      break
    case 'oldest':
      result.sort((a, b) => new Date(a.lastWatchTime) - new Date(b.lastWatchTime))
      break
    case 'name':
      result.sort((a, b) => a.title.localeCompare(b.title))
      break
  }

  return result
})

const totalPages = computed(() => Math.ceil(filteredHistory.value.length / pageSize))

const paginatedHistory = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredHistory.value.slice(start, end)
})

// 方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const calculateProgress = (item) => {
  return Math.round((item.lastEpisode / item.totalEpisodes) * 100)
}

const getStatusText = (status) => {
  const statusMap = {
    watching: '在看',
    finished: '已看完',
    dropped: '已弃番'
  }
  return statusMap[status] || status
}

const handleImageError = (e) => {
  e.target.src = 'https://via.placeholder.com/150x200?text=封面加载失败'
}

const continueWatching = (item) => {
  router.push(`/anime/play/${item.id}/${item.lastEpisode}`)
}

const removeFromHistory = (id) => {
  const index = animeHistory.findIndex(item => item.id === id)
  if (index !== -1) {
    animeHistory.splice(index, 1)
    // 如果删除后当前页没有数据且不是第一页，则返回上一页
    if (paginatedHistory.value.length === 0 && currentPage.value > 1) {
      currentPage.value--
    }
  }
}

const clearAllHistory = () => {
  if (confirm('确定要清空所有观看历史记录吗？此操作不可恢复！')) {
    animeHistory.splice(0, animeHistory.length)
    currentPage.value = 1
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const sortHistory = () => {
  currentPage.value = 1
}

const filterHistory = () => {
  currentPage.value = 1
}

// 初始化
onMounted(() => {
  // 这里可以添加从API获取历史记录的逻辑
  // fetchAnimeHistory()
})
</script>

<style scoped>
.anime-history-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-group label {
  margin-right: 10px;
  font-weight: bold;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.clear-btn {
  padding: 8px 16px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background-color: #ff7875;
}

.history-list {
  margin-top: 20px;
}

.empty-tip {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.empty-tip p {
  font-size: 18px;
  margin-bottom: 20px;
}

.browse-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: bold;
}

.browse-link:hover {
  text-decoration: underline;
}

.history-item {
  display: flex;
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.history-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.anime-cover {
  width: 120px;
  height: 160px;
  margin-right: 20px;
  flex-shrink: 0;
}

.anime-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.anime-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.anime-title {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.anime-title a {
  color: #333;
  text-decoration: none;
}

.anime-title a:hover {
  color: #1890ff;
}

.meta-info {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.episode {
  color: #1890ff;
  font-weight: bold;
}

.progress {
  color: #52c41a;
}

.status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status.watching {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status.finished {
  background-color: #f6ffed;
  color: #52c41a;
}

.status.dropped {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.watch-info {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  color: #888;
  font-size: 13px;
}

.actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
}

.continue-btn, .remove-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.continue-btn {
  background-color: #1890ff;
  color: white;
}

.continue-btn:hover {
  background-color: #40a9ff;
}

.remove-btn {
  background-color: #f5f5f5;
  color: #666;
}

.remove-btn:hover {
  background-color: #e8e8e8;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  gap: 20px;
}

.page-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}
</style>
